package it.uiip.crm.persistenza;

import it.uiip.crm.model.Anagrafica;
import it.uiip.crm.model.Utente;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

public class DAOAnagrafica {
    
	public static Anagrafica findByCodFiscale(String cf) throws DAOException {
        Anagrafica anagrafica = null;
        try {
            Session session = PersistenceManager.getSession();
            Query query = session.createQuery("from Anagrafica where cf = ?");
            query.setString(0, cf);
            List<Anagrafica> risultato = query.list();
            if (risultato.size() != 0) {
            	anagrafica = risultato.get(0);
            }
        } catch (HibernateException e) {
            throw new DAOException(e);
        }
        return anagrafica;
    }

    public static void makeRefresh(Anagrafica anagrafica) throws DAOException {
        PersistenceManager.beginTransaction();
        try {
            PersistenceManager.refreshObject(anagrafica);
        } catch (HibernateException e) {
            PersistenceManager.rollbackTransaction();
            throw new DAOException(e);
        }
    }
    
    public static void makePersistent(Anagrafica anagrafica) throws DAOException {
        PersistenceManager.beginTransaction();
        try {
            PersistenceManager.getSession().saveOrUpdate(anagrafica);
            PersistenceManager.commitTransaction();
        } catch (HibernateException e) {
            PersistenceManager.rollbackTransaction();
            throw new DAOException(e);
        }
    }
    
    public static void makeTransient(Anagrafica anagrafica) throws DAOException {
        PersistenceManager.beginTransaction();
        try {
            PersistenceManager.getSession().delete(anagrafica);
            PersistenceManager.commitTransaction();
        } catch (HibernateException e) {
            PersistenceManager.rollbackTransaction();
            throw new DAOException(e);
        }
    }
}
